import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import {formatParameter} from './index'
import { API_URL } from './apiBaseUrl'

// request interceptor
axios.interceptors.request.use(config => {

  if (store.getters.language) {
    config.headers['accept-language'] = store.getters.language
  }
	
	/^http/.test(config.url) || (config.url = API_URL + config.url);
		

  config.headers['Content-Type'] = 'application/json'
  config.headers['token'] = store.getters.token || ''
  config.withCredentials = false
  if (config.method === 'delete') {
    for (var key in config.data) {
      /\?/.test(config.url) ? config.url += '&' + `${key}=${config.data[key]}` : config.url += '?' + `${key}=${config.data[key]}`
    }
    delete config.data
  }
  formatParameter(config.params || config.data)
  return config
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use(
  response => {

    if (response.data.status === 200 || response.data.message === 'query ok') {
      return response
    }
    const res = response.data

    if (res.code === 4101) {
      store.dispatch('FedLogOut').then(() => {
        Message.error('状态过期，请重新登录！')
        setTimeout(() => {
          location.reload()
        }, 1000)
        // location.href=location.origin+location.pathname+'#/login'
      })
    } else if (res.code !== 0 && res.code !== 4002) {
      Message({
        message: res.msg,
        type: 'error'
      })
      // Message.error(res.msg)
    }
    return response
  },
  error => {

    if (error && error.response.status >= 400) {
      if (error.response.status === 500) {
        Message({
          message: '数据异常，请刷新后重试，或联系管理员！',
          type: 'error'
        })
        // Message.error('数据异常，请刷新后重试，或联系管理员！')
      } else if (error.response.status === 429) {
        Message({
          message: '操作太频繁，请稍后重试！',
          type: 'error'
        })
        // Message.error('操作太频繁，请稍后重试！')
      } else {
        Message({
          message: error.response.data.message ? error.response.data.message : '服务器异常',
          type: 'error'
        })
        // Message.error(error.response.data.message ? error.response.data.message : '管理员炸了，服务器跑路了！！！')
      }
    }
  })

export default axios
